package activity;

import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.app.AlarmManager;
import android.app.Dialog;

import android.animation.ValueAnimator.AnimatorUpdateListener;

import android.app.Notification;
import android.app.NotificationManager;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;

import android.os.CountDownTimer;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;

import android.os.IBinder;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.lanou.horo.myapplication.R;

import application.BasisApplication;
import cn.jpush.android.api.JPushInterface;
import dbdao.HistoryDBhelper;
import de.greenrobot.event.EventBus;
import fragment.PlayFragment;
import fragment.tabhostFragment.MainFragment;
import service.MusicService;
import utils.roundimage.RoundNetWorkImageView;
import volley.VolleySingleton;

/**
 * 主要activity 播放按钮
 * Created by dllo on 15/11/16.
 */
public class MainActivity extends AbsBaseActivity implements View.OnClickListener {
    private ImageView main_play_button, main_play_button_b;
    private long exitTime = 0;
    private RoundNetWorkImageView main_play_button_bac;
    private Animation animation;
    private MusicService musicService;
    private int mScreenWidth;


    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";

    public MusicService getMusicService() {
        return musicService;
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicService.ServiceBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
        }
    };

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//    }

//    @Override
//    protected void onStart() {
//        super.onStart();
////        startService(new Intent(this, MusicService.class));
//
//    }


//    /**
//     * 该方法与发布者同一个线程执行
//     * @param imageUrl
//     */
//    public void onEvent(String imageUrl) {
//
//    }

    /**
     * 该方法在ui主线程执行
     */
    public void onEventMainThread(String imageUrl) {
        VolleySingleton.getInstance().getBitmap(imageUrl, main_play_button_bac);
    }


    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        main_play_button_b = findView(R.id.main_play_button_b);
        main_play_button = findView(R.id.main_play_button);
        main_play_button_bac = findView(R.id.main_play_button_bac);
    }

    @Override
    protected void initData() {

        setAnimator();
        EventBus.getDefault().register(this); //注册EventBus
//        startService(new Intent(this, MusicService.class));
        if (musicService == null) {
            bindService(new Intent(this, MusicService.class),
                    connection, Context.BIND_AUTO_CREATE);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(ALARM_CLOCK_BROADCAST);
        registerReceiver(mAlarmReceiver, filter);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        main_play_button.setOnClickListener(this);
        main_play_button_b.setOnClickListener(this);

        MainFragment m = new MainFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.layout_replace, m, "m");
        ft.commitAllowingStateLoss();
        if (HistoryDBhelper.getInstance().queryAll() !=
                null && HistoryDBhelper.getInstance().queryAll().size() > 0) {
            VolleySingleton.getInstance().getBitmap(HistoryDBhelper.getInstance().queryAll().get(HistoryDBhelper.
                    getInstance().queryAll().size() - 1).getSmallLogo(), main_play_button_bac);
        }

    }

    Animation an;

    /***
     * 旋转动画
     * <p/>
     * <p/>
     * /**
     * 设置动画
     */
    public void rotateImpl() {
        an = AnimationUtils.loadAnimation(this,
                R.anim.rotate);
        an.setInterpolator(new LinearInterpolator());
    }


    ObjectAnimator animator;

    public void setAnimator() {//属性动画播放
        animator = ObjectAnimator.ofFloat(main_play_button_bac, "rotation", 0, 360);
        animator.setDuration(4000);
        animator.setRepeatCount(-1);
        animator.setRepeatMode(ObjectAnimator.RESTART);
        animator.setInterpolator(new LinearInterpolator());//匀速

        //WrapMode为LOOp
        /**
         * android:pivotX="50%"
         android:pivotY="50%"
         android:duration="5000"
         android:toDegrees="360"
         android:repeatCount="-1"
         */

    }


    MyAnimatorUpdateListener updateListener = new MyAnimatorUpdateListener();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_play_button://点击圆形动画按钮
                main_play_button.setVisibility(View.GONE);
//                rotateImpl();//开启动画

                if (updateListener.isPause) {
                    updateListener.play();
                }
                //否则就是从头开始播放
                else {
                    animator.start();
                }

                if (BasisApplication.getUserId() == 0) {
                    if (HistoryDBhelper.getInstance().queryAll() != null && HistoryDBhelper.
                            getInstance().queryAll().size() > 0) {
                        toPlayFR(HistoryDBhelper.getInstance().queryAll().get(HistoryDBhelper.
                                getInstance().queryAll().size() - 1).getTrackId());

                    } else {
                        Toast.makeText(this, "请先选择播放内容", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    toPlayFR(BasisApplication.getUserId());
                }
                break;
            case R.id.main_play_button_b:
                toPlayFR(BasisApplication.getUserId());

                break;
        }
    }


    private void toPlayFR(long id) {
        PlayFragment f = new PlayFragment(id);
        getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(
                        R.anim.push_shang_in,
                        R.anim.no_push,
                        R.anim.no_push,
                        R.anim.push_shang_out)
                .add(R.id.replace_all, f)
                .addToBackStack(null)
                .commitAllowingStateLoss();
    }


    //设置睡眠
    public void showSleepDialog() {
        if (BasisApplication.mIsSleepClockSetting) {
            cancleSleepClock();
            Toast.makeText(getApplicationContext(), "已经取消睡眠模式！", Toast.LENGTH_SHORT).show();
            return;
        }
        //弹出睡眠的弹出框
        View view = View.inflate(this, R.layout.sleep_time, null);
        final Dialog dialog = new Dialog(this, R.style.lrc_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        // lp.x = 100; // 新位置X坐标
        // lp.y = 100; // 新位置Y坐标
        lp.width = (int) (mScreenWidth * 0.7); // 宽度
        // lp.height = 400; // 高度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);
        dialog.show();
        final Button cancleBtn = (Button) view.findViewById(R.id.cancle_btn);
        final Button okBtn = (Button) view.findViewById(R.id.ok_btn);
        final EditText timeEt = (EditText) view.findViewById(R.id.time_et);
        View.OnClickListener listener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == cancleBtn) {
                    dialog.dismiss();
                } else if (v == okBtn) {
                    String timeS = timeEt.getText().toString();
                    if (TextUtils.isEmpty(timeS)
                            || Integer.parseInt(timeS) == 0) {
                        Toast.makeText(getApplicationContext(), "输入无效！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setSleepClock(timeS);//调用设置睡眠的时间
                    dialog.dismiss();
                }
            }
        };
        cancleBtn.setOnClickListener(listener);
        okBtn.setOnClickListener(listener);
    }

    /**
     * 设置睡眠闹钟  将在多少秒钟之后推出
     *
     * @param timeS
     */
    private void setSleepClock(String timeS) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(timeS);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        BasisApplication.mIsSleepClockSetting = true;
        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后进入睡眠", Toast.LENGTH_SHORT)
                .show();

    }

    /**
     * 取消睡眠闹钟
     */
    public void cancleSleepClock() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pendingIntent);
        BasisApplication.mIsSleepClockSetting = false;
    }

    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            //退出程序
//            finish();
//            musicService.mediaPlayer.start();
            musicService.pause();

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);  //取消注册
//        stopService(new Intent(this, MusicService.class));
        unbindService(connection);

        //完全退出程序
//        android.os.Process.killProcess(android.os.Process.myPid());//获取PID
        unregisterReceiver(mAlarmReceiver);
        cancleSleepClock();
//        System.exit(0);
    }



    /**
     * 再按一次返回键退出
     *
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                showCustomToast("再按一次返回退出", R.mipmap.play_bg_new);
//                exitTime = System.currentTimeMillis();
//            } else {
//                finish();
//                System.exit(0);
//            }
            FragmentManager fm = null;
            if (fm == null) {
                fm = getSupportFragmentManager();
            }
            if (fm.getBackStackEntryCount() != 0) {
                fm.popBackStack();
                fm.popBackStackImmediate("", 1);
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 更新动画的内部类
     */
    class MyAnimatorUpdateListener implements AnimatorUpdateListener {
        /**
         * 暂停状态
         */
        private boolean isPause = false;
        /**
         * 是否已经暂停，如果一已经暂停，那么就不需要再次设置停止的一些事件和监听器了
         */
        private boolean isPaused = false;
        /**
         * 当前的动画的播放位置
         */
        private float fraction = 0.0f;
        /**
         * 当前动画的播放运行时间
         */
        private long mCurrentPlayTime = 0l;

        /**
         * 是否是暂停状态
         *
         * @return
         */
        public boolean isPause() {
            return isPause;
        }

        /**
         * 停止方法，只是设置标志位，剩余的工作会根据状态位置在onAnimationUpdate进行操作
         */
        public void pause() {
            isPause = true;
        }

        public void play() {
            isPause = false;
            isPaused = false;
        }

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            /**
             * 如果是暂停则将状态保持下来，并每个刷新动画的时间了；来设置当前时间，让动画
             * 在时间上处于暂停状态，同时要设置一个静止的时间加速器，来保证动画不会抖动
             */
            if (isPause) {
                if (!isPaused) {
                    //	mCurrentPlayTime = animation.getCurrentPlayTime();
                    fraction = animation.getAnimatedFraction();
                    animation.setInterpolator(new TimeInterpolator() {
                        @Override
                        public float getInterpolation(float input) {
                            return fraction;
                        }
                    });
                    isPaused = true;
                }
                //每隔动画播放的时间，我们都会将播放时间往回调整，以便重新播放的时候接着使用这个时间,同时也为了让整个动画不结束
                new CountDownTimer(ValueAnimator.getFrameDelay(), ValueAnimator.getFrameDelay()) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                    }

                    @Override
                    public void onFinish() {
                        animator.setCurrentPlayTime(mCurrentPlayTime);
                    }
                }.start();
            } else {
                //将时间拦截器恢复成线性的，如果您有自己的，也可以在这里进行恢复
                animation.setInterpolator(null);
            }
        }

    }
}


//动态刷新ui
//        this.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(MainActivity.this, "123", Toast.LENGTH_SHORT).show();
//                Log.d("MainActivity", "123");
//            }
//        });
